package com.cloudfun.campusshare.configuration.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * Created by Huqin on 2020/4/1
 */
@Slf4j
@Component
public class RabbitMsgCallback implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    /**
     * 接收发送后确认信息
     *
     * @param correlationData
     * @param ack
     * @param cause
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String correlationDataId = Optional.ofNullable(correlationData).flatMap(data -> Optional.ofNullable(data.getId())).orElse("");
        if (ack) {
            log.debug("消息发送成功, id: {}", correlationDataId);
        } else {
            log.error("消息发送失败, id: {}, 原因: {}", correlationDataId, cause);
        }
    }

    /**
     * 发送失败的回调
     *
     * @param message
     * @param replyCode
     * @param replyText
     * @param exchange
     * @param routingKey
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        String correlationDataId = Optional.ofNullable(message.getMessageProperties()).flatMap(data -> Optional.ofNullable(data.getCorrelationId())).orElse("");
        log.error("消息：{}, 发送失败, replyCode：{}, replyText：{} exchange: {}  routingKey: {}", correlationDataId, replyCode, replyText, exchange, routingKey);
    }
}